﻿using System;

namespace NEnsure.Rules
{
	public class SameAsRule<T> : BaseBusinessRule<T>, IBusinessRule<T> where T : IComparable<T>
	{
		protected readonly string _otherPropertyName;
		protected readonly T _otherPropertyValue;

		public override string RuleKey
		{
			get { return "Same-As Rule"; }
		}

		public SameAsRule(string otherPropertyName, T otherPropertyValue)
			: base("{key}'s value ('{value}') needs to be the same as " + otherPropertyName + "'s value ('" + otherPropertyValue + "')")
		{
			_otherPropertyName = otherPropertyName;
			_otherPropertyValue = otherPropertyValue;
		}

		public virtual bool IsBrokenBy(T value)
		{
			if (object.Equals(value, null))
			{
				if (object.Equals(_otherPropertyValue, null))
				{
					return true;
				}

				return false; 
			}

			return value.CompareTo(_otherPropertyValue) != 0;
		}
	}

	public class SameAsRule : SameAsRule<string>
	{
		private bool _ignoreCase;

		public SameAsRule(string otherPropertyName, string otherPropertyValue, bool ignoreCase) 
			: base(otherPropertyName, otherPropertyValue)
		{
			_ignoreCase = ignoreCase;
		}

		public override bool IsBrokenBy(string value)
		{
			if (!_ignoreCase)
			{
				return base.IsBrokenBy(value);
			}

			if (string.IsNullOrEmpty(value) && string.IsNullOrEmpty(_otherPropertyValue))
			{
				return false; 
			}

			return !value.Equals(_otherPropertyValue, StringComparison.InvariantCultureIgnoreCase);
		}
	}
}
